<template>
  <a-drawer
    class="isv-pay-draggable"
    title="支付配置"
    width="calc(100% - 100px)"
    :open="open"
    :bodyStyle="{ padding: 0 }"
    @close="onCancel"
    destroyOnClose
  >
    <!-- 抽屉主要容器 -->
    <div ref="scrollContainerRef" class="draggable-modal-scroll-container">
      <a-tabs activeKey="params-rate" centered>
        <!-- 参数及费率填写区域 -->
        <a-tab-pane key="params-rate" tab="参数及费率的填写" class="tab-pane-container">
          <!---------- 搜索表单区域 ----------->
          <SearchFormTemplate ref="searchFormRef" :searchConfig="searchConfig" />

          <!-- 格栅布局，一行5个卡片 使用数据【id、img、background、title、code】 -->
          <div class="grid-container">
            <a-card
              v-for="item in channelList"
              hoverable
              :key="item.channel_code"
              :class="`channel-item-container${activeChannelId === item.channel_code ? ' active' : ''}`"
              @click="activeChannelId = item.channel_code"
            >
              <a-flex align="center" :gap="12">
                <!-- 渠道图片 -->
                <a-badge :offset="[-8, 42]">
                  <div class="img-container" :style="{ background: item.bg_color || '#000000' }">
                    <img class="img" :src="item.icon" />
                  </div>
                  <!-- 右下角高亮 小圆点 -->
                  <template #count> <div class="dot"></div> </template>
                </a-badge>
                <!---------- 渠道信息 ----------->
                <a-flex vertical>
                  <span class="title">{{ item.channel_name }}</span>
                  <span class="desc">{{ item.channel_code }}</span>
                </a-flex>
              </a-flex>
            </a-card>
          </div>

          <!-- 标签页表单区域 -->
          <a-form
            v-if="activeChannelId !== undefined"
            ref="paramsRateFormRef"
            class="form-container"
            name="params_rate"
            :model="formData"
            :rules="rules"
            :labelCol="{ style: { width: '140px' } }"
            labelWrap
          >
            <a-tabs v-model:activeKey="activeFormDataKey">
              <!-- 参数配置表单区域 -->
              <a-tab-pane key="isvParamsFormData" tab="参数配置">
                <template v-if="activeFormDataKey === 'isvParamsFormData'">
                  <!-- 使用自定义的 formConfig 来渲染表单 -->
                  <FormItemTemplate
                    :formConfig="formConfig"
                    :formData="formData.isvParamsFormData"
                    :parentName="['isvParamsFormData']"
                  />

                  <a-divider orientation="left">渠道参数配置</a-divider>

                  <!-- 动态表单 -->
                  <FormItemTemplate
                    :formConfig="isvParamsFormConfig"
                    :formData="formData.isvParamsFormData"
                    :parentName="['isvParamsFormData']"
                  />
                </template>
              </a-tab-pane>

              <!-- 费率配置表单区域 -->
              <!-- TODO: 费率配置表单区域，整体表单是写死的，字段根据实际数据调整【title、id、expand、enable、facilitator、agent、merchant】 -->
              <a-tab-pane class="rates-form-container" key="ratesFormData" tab="费率配置">
                <template v-if="activeFormDataKey === 'ratesFormData'">
                  <div v-if="filteredRatesFormConfig.length === 0" style="text-align: center; padding: 40px">
                    <p>暂无费率配置信息</p>
                    <p style="color: #999; font-size: 12px">请检查所选渠道是否配置了费率信息</p>
                  </div>
                  <template v-else>
                    <a-card
                      v-for="(item, index) in filteredRatesFormConfig"
                      :key="item.rateId"
                      :title="item.title"
                      :headStyle="{ background: '#fafafa' }"
                    >
                      <template #extra>
                        <a-flex>
                          <a-form-item
                            v-if="formData.ratesFormData[index] && formData.ratesFormData[index].enable"
                            class="rates-form-item-switch"
                            label="是否可进件"
                            :name="['ratesFormData', index, 'expand']"
                          >
                            <a-switch v-model:checked="formData.ratesFormData[index].expand" />
                          </a-form-item>
                          <a-form-item class="rates-form-item-switch" label="是否开通" :name="['ratesFormData', index, 'enable']">
                            <a-switch v-model:checked="formData.ratesFormData[index].enable" />
                          </a-form-item>
                        </a-flex>
                      </template>

                      <a-row v-if="formData.ratesFormData[index] && formData.ratesFormData[index].enable" :gutter="20">
                        <a-col :span="24 / 3">
                          <a-form-item
                            label="服务商底价费率"
                            :rules="{ required: true, message: '请输入服务商底价费率' }"
                            :name="['ratesFormData', index, 'facilitator']"
                          >
                            <a-input-number v-model:value="formData.ratesFormData[index].facilitator" style="width: 100%">
                              <template #addonAfter><PercentageOutlined /></template>
                            </a-input-number>
                          </a-form-item>
                        </a-col>
                        <a-col :span="24 / 3">
                          <a-form-item label="代理商默认费率" :name="['ratesFormData', index, 'agent']">
                            <a-input-number v-model:value="formData.ratesFormData[index].agent" style="width: 100%">
                              <template #addonAfter><PercentageOutlined /></template>
                            </a-input-number>
                          </a-form-item>
                        </a-col>
                        <a-col :span="24 / 3">
                          <a-form-item label="商户进件默认费率" :name="['ratesFormData', index, 'merchant']">
                            <a-input-number v-model:value="formData.ratesFormData[index].merchant" style="width: 100%">
                              <template #addonAfter><PercentageOutlined /></template>
                            </a-input-number>
                          </a-form-item>
                        </a-col>
                      </a-row>

                      <!-- 如果该费率配置未启用，显示提示信息 -->
                      <div v-else style="text-align: center; padding: 20px; color: #999">该费率配置未开通</div>
                    </a-card>
                  </template>
                </template>
              </a-tab-pane>
            </a-tabs>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 抽屉底部按钮 -->
    <template v-if="activeChannelId !== undefined" #footer>
      <!-- 固钉，将按钮固定在 抽屉主要容器 的底部 -->
      <a-affix :target="() => scrollContainerInstance">
        <a-flex justify="center" align="center" :gap="20">
          <a-button type="primary" @click="onFinish">
            <template #icon><CheckOutlined /></template>
            <span>保存</span>
          </a-button>
        </a-flex>
      </a-affix>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
  import { computed, onMounted, reactive, ref, useTemplateRef, watch } from 'vue';
  import { CheckOutlined, PercentageOutlined } from '@ant-design/icons-vue';
  import SearchFormTemplate, { type SearchFormItem } from '@/components/template/form/search-form-template.vue'; // 搜索区模版
  import { bizApi } from '@/api/biz';
  import { message, type FormInstance } from 'ant-design-vue';
  import { Rules } from '@/utils/utils';
  import FormItemTemplate, { type FormItemTemplateConfig } from '@/components/template/form-item/form-item-template.vue';
  import type { Rule } from 'ant-design-vue/es/form';
  import { apiResult } from './api-result';

  /** ================================= 【基础数据/事件定义】 ================================= */
  const open = ref(false); // 控制弹窗显示、隐藏
  const loading = ref(false); // 抽屉加载中
  const editRecord = ref<any>(); // 要修改的记录完整数据
  const scrollContainerInstance = useTemplateRef('scrollContainerRef'); // 滚动容器引用
  const emits = defineEmits<{ dataReload: [] }>(); // 通知调用组件(父组件) 执行 父组件 的 @dataReload 的方法
  /* [关闭抽屉] 1. 重置表单 2. 关闭弹窗 */
  function onCancel() {
    if (paramsRateFormRef.value) {
      paramsRateFormRef.value.clearValidate();
      paramsRateFormRef.value.resetFields();
    }
    activeChannelId.value = undefined;
    activeFormDataKey.value = 'isvParamsFormData';
    open.value = false;

    // 正确初始化表单数据
    formData.isvParamsFormData = {};
    formData.ratesFormData = [];
    delete formData.currentChannelConfigId;
  }

  /* [显示抽屉] 1. 接收参数 2.显示弹窗  */
  function show(record: any) {
    // 初始化所有表单数据
    formData.isvParamsFormData = {};
    formData.ratesFormData = [];
    delete formData.currentChannelConfigId;

    // 重置激活状态
    activeChannelId.value = undefined;
    activeFormDataKey.value = 'isvParamsFormData';

    editRecord.value = record;
    open.value = true;
  }

  defineExpose({ show }); //暴露接口 show(显示弹窗) 方法，供 父组件 调用

  // 表单引用
  const paramsRateFormRef = useTemplateRef('paramsRateFormRef');
  /** ================================= 【未实现的搜索功能】 ================================= */
  // 搜索表单引用
  const searchFormInstance = useTemplateRef('searchFormRef');
  /* TODO: 搜索功能未实现 [搜索配置] */
  const searchConfig: SearchFormItem[] = [
    { title: '渠道名称', dataIndex: 'isv_name', type: 'input' as const, width: 150 },
    { title: '渠道代码', dataIndex: 'isv_code', type: 'input' as const, width: 150 },
  ];

  /** ================================= 【抽屉主要容器区域】 ================================= */
  // 激活的渠道 [这里通过 channelId 作为唯一字段进行数据匹配]
  const activeChannelId = ref<number>();
  // TODO: 渠道列表 数据格式仅做参考
  const channelList = ref(apiResult);

  // TODO: 表单数据，key 是什么类型由实际接口决定
  const formData = reactive<{
    isvParamsFormData: Record<string, any>;
    ratesFormData: Record<string, any>[];
    currentChannelConfigId?: number;
  }>({
    isvParamsFormData: {},
    ratesFormData: [],
    currentChannelConfigId: undefined,
  });
  // 修复：将类型改为 string 类型
  const activeFormDataKey = ref<string>('isvParamsFormData');
  // 表单引用
  const formInstance = useTemplateRef<FormInstance>('paramsRateFormRef');

  /* [发送请求获取渠道列表] */
  async function getChannelList() {
    loading.value = true;
    // TODO: 修改为真实的接口action
    const channelAction = 'base.manage.channel.ServiceImpl.list';
    try {
      const result = await bizApi.httpList(channelAction, { id: editRecord.value?.isv_id });
      channelList.value = result || []; //列表数据
    } catch (error) {
      // TODO: 接口完成后解开注释
      channelList.value = [];
      loading.value = false;
      return Promise.reject(error);
    }
    loading.value = false;
  }
  onMounted(() => {
    getChannelList();
  });
  // 激活的渠道改变时，获取不同的渠道参数表单配置，并进行 [数据回显]
  watch(activeChannelId, async (val) => {
    if (val === undefined) {
      return;
    }

    try {
      // 查询当前ISV在该渠道下是否已有配置
      const queryAction = 'base.manage.isvchannel.ServiceImpl.list';

      // 先用list方法获取所有数据
      const result = await bizApi.httpList(queryAction, {});

      if (result && result.length > 0) {
        // 在前端进行过滤，找到匹配当前ISV和渠道的配置
        const channelConfig = result.find((item: any) => item.isv_id == editRecord.value?.isv_id && item.channel_code === val);

        if (channelConfig) {
          // 保存已有配置的ID，用于更新操作
          formData.currentChannelConfigId = channelConfig.isv_channel_id;

          // 初始化表单数据对象
          const formDataToSet: Record<string, any> = {};

          // 处理静态表单数据（直接字段）
          formDataToSet['isv_channel_status'] =
            channelConfig.isv_channel_status !== undefined ? channelConfig.isv_channel_status : 1;
          formDataToSet['billing_cycle'] = channelConfig.billing_cycle !== undefined ? channelConfig.billing_cycle : 1;
          formDataToSet['expand_status'] = channelConfig.expand_status !== undefined ? channelConfig.expand_status : 1;
          formDataToSet['withdraw_status'] = channelConfig.withdraw_status !== undefined ? channelConfig.withdraw_status : 1;
          formDataToSet['statement_status'] = channelConfig.statement_status !== undefined ? channelConfig.statement_status : 1;

          // 处理动态表单数据（存储在 isv_params 中的 JSON 数据）
          if (channelConfig.isv_params) {
            try {
              const dynamicParams =
                typeof channelConfig.isv_params === 'string' ? JSON.parse(channelConfig.isv_params) : channelConfig.isv_params;
              // 将动态参数合并到表单数据中
              Object.assign(formDataToSet, dynamicParams);
              // 特殊处理字段名映射（如果需要）
              // 如果后端返回的是驼峰命名而前端表单使用下划线命名
              Object.keys(dynamicParams).forEach((key) => {
                const underscoreKey = key.replace(/([A-Z])/g, '_$1').toLowerCase();
                if (underscoreKey !== key) {
                  formDataToSet[underscoreKey] = dynamicParams[key];
                }
              });
            } catch (e) {}
          }

          // 设置表单数据
          formData.isvParamsFormData = formDataToSet;
        } else {
          // 没有找到配置
          formData.isvParamsFormData = {};
          delete formData.currentChannelConfigId;
        }
      } else {
        // 如果没有配置，初始化为空对象
        formData.isvParamsFormData = {};
        delete formData.currentChannelConfigId;
      }
    } catch (error) {
      // 出错时也初始化为空对象
      formData.isvParamsFormData = {};
      delete formData.currentChannelConfigId;
    }

    // 同时初始化费率配置数据
    await initializeRatesFormData();
  });

  // 初始化费率表单数据
  async function initializeRatesFormData() {
    // 清空现有的费率数据
    formData.ratesFormData = [];

    if (activeChannelId.value === undefined) {
      return;
    }

    const channel = channelList.value.find((channel) => channel.channel_code === activeChannelId.value);
    if (!channel) {
      return;
    }

    try {
      // 从 isv_rate_config 表获取费率配置数据
      const rateConfigAction = 'base.manage.isvrateconfig.ServiceImpl.list';
      const rateResult = await bizApi.httpList(rateConfigAction, {
        isv_id: editRecord.value?.isv_id,
        channel_code: activeChannelId.value,
      });

      // 根据 pay_way_codes 过滤费率配置
      const filteredConfig = await getFilteredRatesConfig(channel);

      if (rateResult && rateResult.length > 0) {
        // 如果有保存的费率数据，则使用保存的数据
        filteredConfig.forEach((config: any, index: number) => {
          // 查找保存的数据中是否有匹配的rateId
          const savedData = rateResult.find((item: any) => item.rate_id === config.rateId);

          formData.ratesFormData[index] = {
            title: config.title,
            rateId: config.rateId,
            expand: savedData?.expand ?? config.expand ?? false,
            enable: savedData?.enable ?? config.enable ?? false,
            facilitator: savedData?.facilitator ?? config.facilitator ?? undefined,
            agent: savedData?.agent ?? config.agent ?? undefined,
            merchant: savedData?.merchant ?? config.merchant ?? undefined,
          };
        });
      } else {
        // 如果没有保存的数据，使用默认配置
        filteredConfig.forEach((config: any, index: number) => {
          formData.ratesFormData[index] = {
            title: config.title,
            rateId: config.rateId,
            expand: config.expand ?? false,
            enable: config.enable ?? false,
            facilitator: config.facilitator ?? undefined,
            agent: config.agent ?? undefined,
            merchant: config.merchant ?? undefined,
          };
        });
      }

      console.log('最终的 ratesFormData:', formData.ratesFormData);
    } catch (e) {
      console.error('获取或解析费率配置失败:', e);
      // 出错时使用默认配置
      try {
        const channel = channelList.value.find((channel) => channel.channel_code === activeChannelId.value);
        if (!channel) return;

        const filteredConfig = await getFilteredRatesConfig(channel);
        filteredConfig.forEach((config: any, index: number) => {
          formData.ratesFormData[index] = {
            title: config.title,
            rateId: config.rateId,
            expand: config.expand ?? false,
            enable: config.enable ?? false,
            facilitator: config.facilitator ?? undefined,
            agent: config.agent ?? undefined,
            merchant: config.merchant ?? undefined,
          };
        });
      } catch (parseError) {
        console.error('解析默认费率配置失败:', parseError);
      }
    }
  }

  // 根据 pay_way_codes 过滤费率配置
  async function getFilteredRatesConfig(channel: any) {
    try {
      // 从后端获取渠道的 pay_way_codes 信息
      const channelAction = 'base.manage.channel.ServiceImpl.list';
      const params = {
        channel_code: channel.channel_code,
      };

      const channelResult = await bizApi.httpList(channelAction, params);

      // 获取当前渠道的 pay_way_codes
      let payWayCodes = '';
      if (channelResult && channelResult.length > 0) {
        payWayCodes = channelResult[0].pay_way_codes || '';
      }

      console.log('获取到的 pay_way_codes:', payWayCodes);
      console.log('原始类型:', typeof payWayCodes);

      // 处理 pay_way_codes 可能是数组的情况
      let payWays = [];
      if (Array.isArray(payWayCodes)) {
        payWays = payWayCodes;
      } else if (typeof payWayCodes === 'string') {
        payWays = payWayCodes.split(',');
      } else {
        console.warn('pay_way_codes 类型未知:', typeof payWayCodes);
        payWays = [];
      }

      console.log('处理后的 payWays:', payWays);

      // 创建默认的费率配置（因为你的 ratesFormConfig 是空的）
      const defaultRatesConfig = [
        {
          title: '微信支付费率配置',
          rateId: 'wechat_rate_001',
          expand: true,
          enable: true,
          facilitator: 0.6,
          agent: 0.7,
          merchant: 0.8,
        },
        {
          title: '支付宝费率配置',
          rateId: 'alipay_rate_001',
          expand: false,
          enable: true,
          facilitator: 0.55,
          agent: 0.65,
          merchant: 0.75,
        },
      ];

      console.log('默认费率配置:', defaultRatesConfig);

      // 如果 pay_way_codes 为空，显示所有配置
      if (!payWays || payWays.length === 0) {
        console.log('payWays 为空，返回所有配置');
        return defaultRatesConfig;
      }

      // 根据 pay_way_codes 过滤配置
      const filteredConfig = defaultRatesConfig.filter((config: any) => {
        // 检查是否匹配微信支付
        if (
          config.rateId &&
          config.rateId.includes('wechat') &&
          (payWays.includes('wechat_jsapi') || payWays.includes('WECHAT_PAY'))
        ) {
          console.log('匹配到微信支付配置:', config.rateId);
          return true;
        }

        // 检查是否匹配支付宝支付
        if (
          config.rateId &&
          config.rateId.includes('alipay') &&
          (payWays.includes('alipay_jsapi') || payWays.includes('ALIPAY'))
        ) {
          console.log('匹配到支付宝配置:', config.rateId);
          return true;
        }

        console.log('未匹配到配置:', config.rateId);
        return false;
      });

      console.log('过滤后的配置:', filteredConfig);
      return filteredConfig;
    } catch (e) {
      console.error('获取渠道支付方式失败:', e);
      return [];
    }
  }

  // 参数表单配置 [根据配置渲染表单]
  const isvParamsFormConfig = computed<FormItemTemplateConfig[]>(() => {
    if (activeChannelId.value === undefined) {
      return [];
    }
    const channel = channelList.value.find((channel) => channel.channel_code === activeChannelId.value);
    if (!channel) {
      return [];
    }
    try {
      // 确保正确解析 isv_params 字段
      const config = JSON.parse(channel.isv_params || '[]');
      return config;
    } catch (e) {
      return [];
    }
  });

  // 费率表单配置 [根据配置渲染表单]
  const ratesFormConfig = computed(() => {
    if (activeChannelId.value === undefined) {
      return [];
    }
    const channel = channelList.value.find((channel) => channel.channel_code === activeChannelId.value);
    if (!channel) {
      return [];
    }
    try {
      const config = JSON.parse(channel.ratesFormConfig || '[]');
      return config;
    } catch (e) {
      console.error('ratesFormConfig: error parsing config', e);
      return [];
    }
  });

  // 根据 pay_way_codes 过滤后的费率配置
  const filteredRatesFormConfig = computed(() => {
    if (activeChannelId.value === undefined) {
      return [];
    }
    const channel = channelList.value.find((channel) => channel.channel_code === activeChannelId.value);
    if (!channel) {
      return [];
    }

    // 直接使用默认配置并根据 pay_way_codes 过滤
    const defaultRatesConfig = [
      {
        title: '微信支付费率配置',
        rateId: 'wechat_rate_001',
        expand: true,
        enable: true,
        facilitator: 0.6,
        agent: 0.7,
        merchant: 0.8,
      },
      {
        title: '支付宝费率配置',
        rateId: 'alipay_rate_001',
        expand: false,
        enable: true,
        facilitator: 0.55,
        agent: 0.65,
        merchant: 0.75,
      },
    ];

    try {
      // 获取当前渠道的 pay_way_codes
      const payWayCodes = channel.pay_way_codes || '';

      // 处理 pay_way_codes 可能是数组的情况
      let payWays = [];
      if (Array.isArray(payWayCodes)) {
        payWays = payWayCodes;
      } else if (typeof payWayCodes === 'string') {
        payWays = payWayCodes.split(',');
      } else {
        payWays = [];
      }

      // 如果 pay_way_codes 为空，显示所有配置
      if (!payWays || payWays.length === 0) {
        return defaultRatesConfig;
      }

      // 根据 pay_way_codes 过滤配置
      return defaultRatesConfig.filter((config: any) => {
        // 检查是否匹配微信支付
        if (
          config.rateId &&
          config.rateId.includes('wechat') &&
          (payWays.includes('wechat_jsapi') || payWays.includes('WECHAT_PAY'))
        ) {
          return true;
        }

        // 检查是否匹配支付宝支付
        if (
          config.rateId &&
          config.rateId.includes('alipay') &&
          (payWays.includes('alipay_jsapi') || payWays.includes('ALIPAY'))
        ) {
          return true;
        }

        return false;
      });
    } catch (e) {
      return defaultRatesConfig;
    }
  });

  // 表单 [校验规则] 通用逻辑
  const rules = computed(() => {
    if (activeChannelId.value === undefined) {
      return {};
    }

    try {
      const channel = channelList.value.find((channel) => channel.channel_code === activeChannelId.value);
      if (!channel) {
        return {};
      }

      const { isvParamsFormConfig } = channel;
      const paramsConfig: any[] = JSON.parse(isvParamsFormConfig || '[]');

      const paramsRules: Record<string, Rule[]> = {};
      // 为动态表单字段创建规则（注意字段路径）
      paramsConfig.forEach((item) => {
        const { required, title, dataIndex, uploadMaxSize, type } = item;

        if (!dataIndex) return;

        // 为动态表单字段创建验证规则，使用正确的表单字段路径
        if (required && type !== 'upload') {
          const message = Rules.getRequiredRuleMessage(item);
          paramsRules[`isvParamsFormData.${dataIndex}`] = Rules.getRequiredRules(message);
        }

        if (required && type === 'upload') {
          const message = Rules.getRequiredRuleMessage(item);
          paramsRules[`isvParamsFormData.${dataIndex}`] = Rules.getRequiredUploadRules(message);
        }

        if (type === 'upload') {
          const max = uploadMaxSize ?? 5;
          const existingRules = paramsRules[`isvParamsFormData.${dataIndex}`] || [];
          paramsRules[`isvParamsFormData.${dataIndex}`] = existingRules.concat(Rules.getUploadFileMaxSizeRules(title, max));
        }
      });

      // 为静态表单字段创建规则
      const staticRules: Record<string, Rule[]> = {};
      formConfig.value.forEach((item) => {
        if (item.required && item.dataIndex) {
          const message = `${item.title}不能为空`;
          staticRules[`isvParamsFormData.${item.dataIndex}`] = Rules.getRequiredRules(message);
        }
      });
      return { ...staticRules, ...paramsRules };
    } catch (error) {
      return {};
    }
  });

  /** ================================= 【表单提交部分逻辑】 ================================= */
  // TODO: update接口 方法名
  const updateAction = 'base.manage.isvchannel.ServiceImpl.saveOrUpdate';
  // 将 formConfig 改为响应式数组
  const formConfig = ref([
    {
      title: '状态',
      dataIndex: 'isv_channel_status',
      type: 'radio' as const,
      required: true,
      defaultValue: 1,
      props: {
        options: [
          { label: '启用', value: 1 },
          { label: '停用', value: 2 },
        ],
      },
    },
    {
      title: '结算周期',
      dataIndex: 'billing_cycle',
      type: 'input-number' as const,
      required: true,
    },
    {
      title: '是否支持进件',
      dataIndex: 'expand_status',
      type: 'radio' as const,
      required: true,
      props: {
        options: [
          { label: '支持', value: 1 },
          { label: '不支持', value: 2 },
        ],
      },
    },
    {
      title: '是否支持提现',
      dataIndex: 'withdraw_status',
      type: 'radio' as const,
      required: true,
      props: {
        options: [
          { label: '支持', value: 1 },
          { label: '不支持', value: 2 },
        ],
      },
    },
    {
      title: '是否支持对账',
      dataIndex: 'statement_status',
      type: 'radio' as const,
      required: true,
      props: {
        options: [
          { label: '支持', value: 1 },
          { label: '不支持', value: 2 },
        ],
      },
    },
  ]);
  /* [提交弹窗] 1. 调用子组件 提交方法 2. 提交成功后，关闭弹窗 3. 刷新父组件数据 */
  async function onFinish() {
    // 优先使用 formInstance，如果不存在则使用 paramsRateFormRef
    const formRef = formInstance.value || paramsRateFormRef.value;
    try {
      // 验证表单
      await formRef.validate();
    } catch (error) {
      message.error('请检查表单填写是否正确');
      return;
    }

    // 检查是否选择了渠道
    if (activeChannelId.value === undefined) {
      message.error('请选择支付渠道');
      return;
    }

    // 获取当前选中的渠道信息
    const currentChannel = channelList.value.find((channel) => channel.channel_code === activeChannelId.value);
    const staticFormData = {}; // 静态表单数据
    const dynamicFormData = {}; // 动态表单数据

    // 根据字段名分离数据
    Object.keys(formData.isvParamsFormData).forEach((key) => {
      // 静态表单字段
      const staticFields = ['isv_channel_status', 'billing_cycle', 'expand_status', 'withdraw_status', 'statement_status'];

      if (staticFields.includes(key)) {
        staticFormData[key] = formData.isvParamsFormData[key];
      } else {
        // 其他字段都归为动态表单数据
        dynamicFormData[key] = formData.isvParamsFormData[key];
      }
    });

    // 合并提交参数
    const mergedParams = {
      ...staticFormData,
      isv_params: JSON.stringify(dynamicFormData),
      rate_params: JSON.stringify(formData.ratesFormData), // 添加费率参数
      // 使用已存在的配置ID或undefined（新增）
      isv_channel_id: formData.currentChannelConfigId,
      // 添加所选支付渠道相关的基本信息
      channel_code: activeChannelId.value,
      channel_name: currentChannel?.channel_name,

      // 从记录中获取需要的字段
      oem_id: editRecord.value?.oem_id,
      oem_name: editRecord.value?.oem_name,
      isv_name: editRecord.value?.isv_name,
      remark: editRecord.value?.remark,
      isv_id: editRecord.value?.isv_id,
      // TODO: 以下字段需要根据实际业务逻辑进行调整，目前写死默认值
      rate_compute_mode: 1,
      mch_mode_status: 1,
      open_expand_status: 1,
      isv_mode_status: 1,
      pay_way_codes: 'WECHAT_PAY,ALIPAY',
    };

    try {
      const ret = await postFormData(updateAction, mergedParams);
      if (ret === true) {
        onCancel();
        emits('dataReload');
      }
    } catch (error) {}
  }

  /* 提交表单数据请求 */
  async function postFormData(action: string, params: Record<string, any>): Promise<boolean> {
    loading.value = true;
    let flag = false; // 默认为false

    try {
      const result = await bizApi.httpSave(action, params);
      message.success({
        content: result.sub_message || '数据保存成功',
      });
      flag = true;
    } catch (error: any) {
      message.error({
        content: error.message || error.sub_message || '数据保存失败',
      });
    }
    loading.value = false;
    return flag;
  }
</script>
<style lang="less" scoped>
  .isv-pay-draggable {
    .draggable-modal-scroll-container {
      height: 100%;
      overflow-y: auto;
      overflow-x: hidden;
      .tab-pane-container {
        padding: 20px 40px;

        .grid-container {
          display: grid;
          /* 一行5列，每列宽度相等 */
          grid-template-columns: repeat(5, 1fr);
          /* 上下左右间距都是20px */
          gap: 20px;
          margin-bottom: 40px;

          .channel-item-container {
            height: 90px;
            // .ant-card-body 卡片内容区域垂直居中
            :deep(.ant-card-body) {
              height: 100%;
              padding: 12px;
              display: flex;
              flex-direction: column;
              justify-content: center;
            }
            .img-container {
              width: 50px;
              height: 50px;
              border-radius: 50px;
              display: flex;
              align-items: center;
              justify-content: center;
              .img {
                max-width: 24px;
                max-height: 24px;
                width: auto;
                height: auto;
              }
            }
            .dot {
              width: 18px;
              height: 18px;
              border-radius: 18px;
              background: rgb(217, 217, 217);
              border: 3px solid #fff;
            }
            .title {
              font-weight: 600;
            }
          }
          .active {
            border: 1px solid #1a79ff;
            background: rgba(25, 121, 255, 0.05);
          }
        }

        .form-container {
          .rates-form-container {
            display: flex;
            flex-direction: column;
            gap: 40px;
            .rates-form-item-switch {
              margin-bottom: 0;
            }
          }
        }
      }
    }
  }
</style>
